<?php
/*************************************************************************

$Id: iclear.php 499 2010-10-06 20:33:34Z dis $

iclear payment system - because secure is simply secure
http://www.iclear.de

Copyright (c) 2001 - 2010 iclear - Christian Arnold

Released under the GNU General Public License

************************************************************************

All rights reserved.

This program is free software licensed under the GNU General Public License (GPL).

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA

*************************************************************************/

class IclearWrapperJTL extends IclearWrapperBase {

	var $lang;
	// iclear DMI -> added global order var
	var $code;

	var $title;

	var $description;

	var $enabled;

	var $order;

	var $orderStatusID;

	var $currentProductID = 0;

	var $specialItemID = 0;

	var $showPriceTax;

	var $otPaymentItemID = 0;

	/**
	 *
	 * @var  Local_Iclear_Sendorderb2c_Model_Iclearpayment
	 * @access protected
	 */
	protected $_payment = null;

	/**
	 *
	 * @var  Mage_Sales_Model_Quote
	 * @access protected
	 */
	protected $_order = null;

	protected $_settings = null;

	protected $_pluginsettings = null;

	protected $_aSession = null;

	var $addressKeysMask = array(
      'name' => '',
      'company' => '',
      'street' => 'info',
      'region' => '',
      'city' => '',
      'postcode' => '',
      'state' => '',
	);

	var $addressKeysUnmask = array(
      'company',
      'street',
      'region',
      'city',
      'postcode',
      'state',
	);

	protected $_shopID = 0;
	
	protected $bIframe = false;
	
	protected $module_name = "";

	// class constructor
	function __construct(&$icCore) {
		$this->icVersion = '$Id$';
		global $icCore;
		parent::IclearWrapperBase($icCore);
		if(!defined('IC_WRAPPER_ID')) {
			die("Wrapper base class 4 oxid not instantiated!\n");
		}

		$this->id = IC_WRAPPER_ID;

		$this->code = 'iclear';
		$lang = $icCore->getLanguage();

		$this->lang =& $lang;
		$this->_installType = 'create';
	}

	/**
	 * Performs a SQL query
	 * @param string $sql
	 */
	function dbQuery( $sql = '' ) {
		return $GLOBALS['DB']->executeExQuery( $sql, 1 );
	}

	/**
	 * Fetch a single record as array from DB
	 * @param string $sql
	 */
	function dbFetchRecord( $sql = '' ) {
		$rec = false;
		if( $rs = $GLOBALS['DB']->executeExQuery( $sql, 1 ) ) {
			$row = mysql_fetch_array( $rs, MYSQL_ASSOC );
			$rec = $row;
		}
		return $rec;
	}

	/**
	 * Last DB insert ID
	 */
	function dbLastInsertID() {
		/*$oDB = oxDb::getDb( true );
		 return $oDB->Insert_ID( );*/
	}

	/**
	 * Entry point of iclear order processing
	 */
	function process( ) {
		if($this->_order) {
			$soap = $this->icCore->getObject('IclearSOAP');
			return $this->icCore->perform($soap, IC_SOAP_SENDORDER_METHOD);
		}
	}

	function setShopID ( $shopID ) {
		$this->_shopID = $shopID;
	}

	function setOrder ( $oOrder ) {
		$this->_order =& $oOrder;
	}

	function setSetting ( $oSettings ) {
		$this->_settings =& $oSettings;
	}

	function setPluginSetting ( $oPluginSettings ) {
		$this->_pluginsettings =& $oPluginSettings;
	}

	/**
	 * get the iclear shopID from config
	 * @return int
	 */
	function shopID() {
		return $this->_shopID;
	}

	/**
	 * get current order
	 * @return object order
	 */
	function getOrder() {
		return $this->_order;
	}

	/**
	 * item count of current order
	 * @return int $count
	 */
	function orderItemCount() {
		$rv = 0;
		$rv = count( $this->_order->Positionen > 0 );
		return $rv;
	}

	/**
	 * get session ID
	 * @return string $sessionID
	 */
	function sessionID() {
		return $this->_order->cSession;
	}

	/**
	 * actual currency ISO3 code, EUR, e.g.
	 * @return string $currency
	 */
	function currency() {
		$currency = null;
		$currency = $this->_order->Waehrung->cISO;
		if ( $currency ) {
			return $currency;
		}
		return '';
	}

	/**
	 * language ISO2 code
	 * @return string
	 */
	function languageISO() {
		return $this->_order->oKunde->cLand; // $_SESSION["cISOSprache"]
	}

	/**
	 * customerID of current order
	 * @return int
	 */
	function customerID() {
		$rv = 0;
		$rv = $this->_order->oKunde->kKunde;
		return $rv;
	}

	/**
	 * Get the current delivery address info from shop-system
	 * @return IclearAddress
	 */
	function &deliveryAddress( ) {
		$rv = false;
		$street = array();

		if( $this->getOrder( ) ) {
			if ( $this->_order->Lieferadresse ) {
				$street = explode( ' ', $this->_order->Lieferadresse->cStrasse );
				$params = array(
				IC_SOAP_ADDRESS_FIRSTNAME => $this->encodeUTF8( $this->_order->Lieferadresse->cVorname ),
				IC_SOAP_ADDRESS_LASTNAME => $this->encodeUTF8( $this->_order->Lieferadresse->cNachname ),
				IC_SOAP_ADDRESS_COMPANY => $this->encodeUTF8( $this->_order->Lieferadresse->cFirma ),
				IC_SOAP_ADDRESS_STREET => $this->encodeUTF8( $this->parseStreet ( $this->_order->Lieferadresse->cStrasse ) ),
				IC_SOAP_ADDRESS_STREET_NO => $this->encodeUTF8( $this->parseStreetNo ( $this->_order->Lieferadresse->cStrasse ) ),
				IC_SOAP_ADDRESS_ZIPCODE => $this->encodeUTF8( $this->_order->Lieferadresse->cPLZ ),
				IC_SOAP_ADDRESS_CITY => $this->encodeUTF8( $this->_order->Lieferadresse->cOrt ),
				);
				if( strlen( $this->_order->Lieferadresse->cLand ) > 2 )
					$params[IC_SOAP_ADDRESS_COUNTRY] = $this->encodeUTF8( landISO( $this->_order->Lieferadresse->cLand ) );
				else
					$params[IC_SOAP_ADDRESS_COUNTRY] = $this->encodeUTF8( $this->_order->Lieferadresse->cLand );
				if ( $this->_order->Lieferadresse->cAnrede == "m" )
					$params[IC_SOAP_ADDRESS_SALUTATION] = 1;
				else if ( $this->_order->Lieferadresse->cAnrede == "w" )
					$params[IC_SOAP_ADDRESS_SALUTATION] = 0;
				else
					$params[IC_SOAP_ADDRESS_SALUTATION] = -1;
			}
			else {
				$street = explode( ' ', $this->_order->oRechnungsadresse->cStrasse );
				$params = array(
				IC_SOAP_ADDRESS_FIRSTNAME => $this->encodeUTF8( $this->_order->oRechnungsadresse->cVorname ),
				IC_SOAP_ADDRESS_LASTNAME => $this->encodeUTF8( $this->_order->oRechnungsadresse->cNachname ),
				IC_SOAP_ADDRESS_COMPANY => $this->encodeUTF8( $this->_order->oRechnungsadresse->cFirma ),
				IC_SOAP_ADDRESS_STREET => $this->encodeUTF8( $this->parseStreet ( $this->_order->oRechnungsadresse->cStrasse ) ),
				IC_SOAP_ADDRESS_STREET_NO => $this->encodeUTF8( $this->parseStreetNo ( $this->_order->oRechnungsadresse->cStrasse ) ),
				IC_SOAP_ADDRESS_ZIPCODE => $this->encodeUTF8( $this->_order->oRechnungsadresse->cPLZ ),
				IC_SOAP_ADDRESS_CITY => $this->encodeUTF8( $this->_order->oRechnungsadresse->cOrt ),
				);
				if( strlen( $this->_order->Lieferadresse->cLand ) > 2 )
				$params[IC_SOAP_ADDRESS_COUNTRY] = $this->encodeUTF8( landISO( $this->_order->oRechnungsadresse->cLand ) );
				else
				$params[IC_SOAP_ADDRESS_COUNTRY] = $this->encodeUTF8( $this->_order->oRechnungsadresse->cLand );
				if ( $this->_order->oRechnungsadresse->cAnrede == "m" )
					$params[IC_SOAP_ADDRESS_SALUTATION] = 1;
				else if ( $this->_order->oRechnungsadresse->cAnrede == "w" )
					$params[IC_SOAP_ADDRESS_SALUTATION] = 0;
				else
					$params[IC_SOAP_ADDRESS_SALUTATION] = -1;
			}

			$address = $this->icCore->getObject('IclearAddress', $instance = true);
			if($address->address($params)) {
				$rv =& $address;
			}
		}
		return $rv;
	}

	/**
	 * next item of current order
	 * @return array icSoapItem
	 */
	function nextOrderItem() {
		$item = false;
		$id =& $this->currentProductID;

		if( is_array( $this->_order->Positionen ) ) {
			if( $id < sizeof( $this->_order->Positionen ) ) {
				$product = $this->_order->Positionen[$id];
				if ( $product->kArtikel ) {
					$item[IC_SOAP_ITEM_NO] = $this->encodeUTF8( $product->cArtNr );
					$item[IC_SOAP_ITEM_TITLE] = $this->encodeUTF8( $product->nAnzahl . ' x ' . $product->Artikel->cName );
					$item[IC_SOAP_ITEM_QTY] = 1;
					$item[IC_SOAP_ITEM_PRICE_NET] = $product->fPreis * $product->nAnzahl;
					$item[IC_SOAP_ITEM_PRICE_GROS] =  berechneBrutto ( ( $product->fPreis * $product->nAnzahl ), $product->fMwSt );
					$item[IC_SOAP_ITEM_VAT_RATE] = $product->fMwSt;
				}
			}
			$id++;
		}
		return $item;
	}

	/**
	 * get all specials items from shop (shipping, coupons) as an array
	 * of BasketItem formatted arrays
	 * @return array
	 */
	function specialItems() {
		$items = false;
		
		if( is_array( $this->_order->Positionen ) ) {
			for( $id = 0; $id < sizeof( $this->_order->Positionen ); $id++ ) {
    			$product = $this->_order->Positionen[$id];
    			
    			if ( $product->kArtikel == '0' ) {
    				$item[IC_SOAP_ITEM_NO] = $this->specialItemID;
    				if ( is_array( $product->cName ) && isset( $product->cName[$_SESSION['cISOSprache']]) )
    					$item[IC_SOAP_ITEM_TITLE] = $this->encodeUTF8( $product->cName[$_SESSION['cISOSprache']] );
    				else
						$item[IC_SOAP_ITEM_TITLE] = $this->encodeUTF8( $product->cName );
					$item[IC_SOAP_ITEM_PRICE_NET] = $product->fPreis;
					$item[IC_SOAP_ITEM_PRICE_GROS] =  berechneBrutto ( $product->fPreis, $product->fMwSt );
					$item[IC_SOAP_ITEM_QTY] = 1;
					$item[IC_SOAP_ITEM_VAT_RATE] = $product->fMwSt;
					$items[] = $item;
    			}
    			if ( is_array( $product->cName ) && isset( $product->cName[$_SESSION['cISOSprache']]) )
    				$item[IC_SOAP_ITEM_TITLE] = $this->encodeUTF8( $product->cName[$_SESSION['cISOSprache']] );
			}
		}
		return $items;
	}

	/**
	 * get the customer register information from shop-system
	 * as an array, formatted 4 direct usage in soap call
	 * @return array
	 */
	function customerInfo() {
		$rv = false;
		$street = array();
		if(!$this->customerInfo) {
			if( $this->getOrder( ) ) {

				$info = array(
				IC_SOAP_REG_CUSTOMER_ACQUISE_ID => 0,
				IC_SOAP_REG_CUSTOMER_BANK_ACCOUNT_ID => '',
				IC_SOAP_REG_CUSTOMER_BANK_BIC => '',
				IC_SOAP_REG_CUSTOMER_BANK_BLZ => '',
				IC_SOAP_REG_CUSTOMER_BANK_CUSTOMER => '',
				IC_SOAP_REG_CUSTOMER_BANK_IBAN => '',
				IC_SOAP_REG_CUSTOMER_BANK_NAME => '',
				IC_SOAP_REG_CUSTOMER_COMPANYNAME => $this->encodeUTF8( $this->_order->oRechnungsadresse->cFirma ),
				IC_SOAP_REG_CUSTOMER_EMAIL => $this->encodeUTF8( $this->_order->oRechnungsadresse->cMail ),
				IC_SOAP_REG_CUSTOMER_FAX => $this->encodeUTF8( $this->_order->oRechnungsadresse->cFax ),
				IC_SOAP_REG_CUSTOMER_FIRSTNAME => $this->encodeUTF8( $this->_order->oRechnungsadresse->cVorname ),
				IC_SOAP_REG_CUSTOMER_DOB => '', //$this->_order->oRechnungsadresse->dGeburtstag  . 'T00:00:00'),
				IC_SOAP_REG_CUSTOMER_INVOICE_CITY => $this->encodeUTF8( $this->_order->oRechnungsadresse->cOrt ),
				IC_SOAP_REG_CUSTOMER_INVOICE_RECEIVER => $this->encodeUTF8( $this->_order->oRechnungsadresse->cVorname . ' ' . $this->_order->oRechnungsadresse->cNachname ),
				IC_SOAP_REG_CUSTOMER_INVOICE_STREET => $this->encodeUTF8( $this->parseStreet ( $this->_order->oRechnungsadresse->cStrasse ) ),
				IC_SOAP_REG_CUSTOMER_INVOICE_STREETNO => $this->encodeUTF8( $this->parseStreetNo ( $this->_order->oRechnungsadresse->cStrasse  ) ),
				IC_SOAP_REG_CUSTOMER_INVOICE_ZIPCODE => $this->encodeUTF8( $this->_order->oRechnungsadresse->cPLZ ),
				IC_SOAP_REG_CUSTOMER_LASTNAME => $this->encodeUTF8( $this->_order->oRechnungsadresse->cNachname ),
				IC_SOAP_REG_CUSTOMER_PHONE => $this->encodeUTF8( $this->_order->oRechnungsadresse->cTel ),
				IC_SOAP_REG_CUSTOMER_EXT_CUSTOMER_ID => $this->encodeUTF8( $this->_order->oRechnungsadresse->kKunde ),
				IC_SOAP_REG_CUSTOMER_NEWSLETTER_FLAG => '',
				);
				if( strlen( $this->_order->oKunde->cLand ) > 2 )
					$info[IC_SOAP_REG_CUSTOMER_INVOICE_COUNTRY] = $this->encodeUTF8( landISO( $this->_order->oRechnungsadresse->cLand ) );
				else 
					$info[IC_SOAP_REG_CUSTOMER_INVOICE_COUNTRY] = $this->encodeUTF8( $this->_order->oRechnungsadresse->cLand );
					
				if ( $this->_order->oRechnungsadresse->cAnrede == "m" )
					$info[IC_SOAP_REG_CUSTOMER_SALUTATION_ID] = 1;
				else if ( $this->_order->oRechnungsadresse->cAnrede == "w" )
					$info[IC_SOAP_REG_CUSTOMER_SALUTATION_ID] = 0;
				else
					$info[IC_SOAP_REG_CUSTOMER_SALUTATION_ID] = -1;

				$this->customerInfo = $info;
			}

		}
		return $this->customerInfo;
	}

	/**
	 * returns the iclear URL to the iclear login page
	 * @return string
	 */
	function iclearURL() {
		$rv = '';
		$basket = $this->icCore->getBasket();
		if($url = $basket->iclearURL()) {
			$rv = $basket->iclearURL();
		}
		return $rv;
	}

	/**
	 * obsolete in magento
	 */
	function finalizeBasket() {
	}

	/**
	 * Abstract method which must be implemented in child classes
	 */
	function storeOrder() {
		die("Store order not implemented in enclosing instance!\n");
	}

	/**
	 * recreates the delivery and billing information of a order
	 */
	function unmaskOrder() {
		$rc = false;
		$basket = $this->icCore->getBasket();
		if($orderID = $basket->orderID()) {
			$order = new Bestellung( $orderID );
			$order->fuelleBestellung( 0 );

			global $oPlugin;
			$oPlugin = new Plugin( gibkPluginAuscModulId( $order->Zahlungsart->cModulId ) );
			if( $oPlugin->kPlugin > 0 ) {
				require_once(PFAD_ROOT . PFAD_PLUGIN . $oPlugin->cVerzeichnis . "/" . PFAD_PLUGIN_VERSION . $oPlugin->nVersion . "/" . PFAD_PLUGIN_PAYMENTMETHOD . $oPlugin->oPluginZahlungsKlasseAssoc_arr[$order->Zahlungsart->cModulId]->cClassPfad);
				$paymentMethod = new $oPlugin->oPluginZahlungsKlasseAssoc_arr[$order->Zahlungsart->cModulId]->cClassName( $order->Zahlungsart->cModulId );
				
				$paymentMethod->cModulId = $order->Zahlungsart->cModulId;
				$paymentMethod->setOrderStatusToPaid( $order );
				$paymentMethod->sendConfirmationMail( $order );
				$rc = true;
			}
		}
		return $rc;
	}

	/**
	 * set the order state 2 cancel
	 * works only with waiting orders
	 * @param int $orderID
	 */
	function cancelOrder($orderID = 0) {
		$rc = false;
		if($orderID) {
			$order = new Bestellung( $orderID );
			$order->fuelleBestellung( 0 );
			
			global $oPlugin;
			$oPlugin = new Plugin( gibkPluginAuscModulId( $order->Zahlungsart->cModulId ) );
			if( $oPlugin->kPlugin > 0 ) {
				require_once(PFAD_ROOT . PFAD_PLUGIN . $oPlugin->cVerzeichnis . "/" . PFAD_PLUGIN_VERSION . $oPlugin->nVersion . "/" . PFAD_PLUGIN_PAYMENTMETHOD . $oPlugin->oPluginZahlungsKlasseAssoc_arr[$order->Zahlungsart->cModulId]->cClassPfad);
				$paymentMethod = new $oPlugin->oPluginZahlungsKlasseAssoc_arr[$order->Zahlungsart->cModulId]->cClassName( $order->Zahlungsart->cModulId );
				
				$paymentMethod->cModulId = $order->Zahlungsart->cModulId;
				$paymentMethod->cancelOrder( $order->kBestellung );
				$paymentMethod->sendMail ( $order->kBestellung, MAILTEMPLATE_BESTELLUNG_STORNO );
				$rc = true;
			}
		}
		return $rc;
	}

	/**
	 * returns the shopURL where the iclear system redirects the customer finally to
	 * called from iclear.php processing endpoint
	 */
	function shopURL() {
		$rv = '';
		$basket =& $this->icCore->getBasket();

		if($basket->orderAccepted()) {
			if($basket->status() == IC_ORDER_CANCEL) {
				$rv = gibShopURL() . "/bestellvorgang.php?editZahlungsart=1";
			} else {
				session_id( $basket->sessionID( ) );
				session_start();
				$rv = $_SESSION['ic_notification_url'] . "&ic_basketID=" . urlencode ( $basket->basketID( ) );
				unset($_SESSION['ic_notification_url']);
			}
		} else {
			$lang =& $this->icCore->getLanguage();
			$soap =& $this->icCore->getObject('IclearSOAP');
			$rv = gibShopURL() . "/bestellvorgang.php?editZahlungsart=1&fehler=" . urlencode( $lang->getParam( 'TRANSACTION_ERROR' ) ) . "&iclearerror=" . urlencode( $soap->lastError( ) );
		}
		return $rv;
	}

	/**
	 * Installs iclear table in DB, if not present
	 */
	function setup( $clean = true ) {
		$rv = false;
		if ( $this->installTable( $clean ) )
			$rv = true;
		return $rv;
	}

	function beforeSessionSave ( ) {
		if ( !is_null( $_SESSION ) ) {
			$this->_aSession = $_SESSION;
			 $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
		}
	}

	function afterSessionSave ( ) {
		if ( !is_null( $this->_aSession ) ) {
			$_SESSION = $this->_aSession;
		}
	}
	
	function setInline ( $inline ) {
		if ( $inline )
			$this->bIframe = true;
		else 
			$this->bIframe = false;
	}
	
	function pageparams ( ) {
		$Param = array( );
		if ( $this->bIframe ) {
			$Param['mode'] = 'inline';
		}
		else {
			$Param['mode'] = 'std';
		}
		return $Param;
	}
	
	function moduleName ( $name ) {
		if ( strlen ( $name  ) > 1 ) {
			$this->module_name = strtoupper( $name );
		}
		else {
			$this->module_name = "";
		}
	}
	
	function paymentType ( ) {
		$rv = false;
		if ( strlen( $this->module_name ) > 0 ) {
			switch ( $this->module_name ) {
				case "INVOICE": 
					$rv = 'bi';
					break;
				case "CREDITCARD":
					$rv = 'cc';
					break;
				case "ONLINEBANKING":
					$rv = 'ob';
					break;
				case "PREPAYMENT":
					$rv = 'ia';
					break;
				default:
					break;	
			}
		}
		return $rv;
	}
	
	function conditionsAccepted ( ) {
		return 1;
	}
}
?>
